﻿using AutoMapper;
using Decoration.Api.Comm;
using Decoration.IService;
using Decoration.Models;
using Decoration.Models.Dto;
using Decoration.Models.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Decoration.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [MyAuthorize]
    public class UserProcedureController : ControllerBase
    {
        private readonly IUserProcedureService svc;
        private readonly IMapper mapper;

        public UserProcedureController(IUserProcedureService svc,IMapper mapper)
        {
            this.svc = svc;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取全部
        /// </summary>
        /// <returns></returns>
        [HttpGet("getAll")]
        public Result Get()
        {
            var data = svc.Query(o => o.Status == 1);

            return new Result() { code = 1, msg = "成功", data = data };
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="projectName"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public PagedResult<UserProcedureDto> Get(string? projectName = "", int pageSize = 10, int pageIndex = 1)
        {

            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                from UserProcedures up
	                inner join ProjectInfos pj on up.ProjectId = pj.Id
	                inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	                    where 1=1";

            if (string.IsNullOrEmpty(sql)) sql += " and projectName like @projectName";

            string totalSql = $"select count(*) from ({sql})";


            int total = svc.ExecuteScalar<int>(sql, new { projectName = $"%{projectName}%" });

            sql += " order by createTime desc";
            sql += " offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";

            var data = svc.Query<UserProcedureDto>(sql, new { projectName = $"%{projectName}%", pageSize, pageIndex });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", total = total, data = data };
        }

        /// <summary>
        /// 我的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet("getMy")]
        public PagedResult<UserProcedureDto> GetMy(string? projectName = "", int pageSize = 10, int pageIndex = 1)
        {
            var auth = RouteData.Values["auth"] as AuthInfo;

            string sql = @"select up.*
		                ,pj.ProjectName
		                ,checkstu.DictName as 'CheckStatusText'
		                ,stu.DictName as 'StatusText'
	                from UserProcedures up
	                inner join ProjectInfos pj on up.ProjectId = pj.Id
	                inner join vw_dict checkstu on up.CheckStatus = checkstu.DictValue and checkstu.DictTypeName = '验收状态'
	                inner join vw_dict stu on up.[Status] = stu.DictValue and stu.DictTypeName = '工序状态'
	                    where Employee = @userId";

            if (string.IsNullOrEmpty(sql)) sql += " and projectName like @projectName";

            string totalSql = $"select count(*) from ({sql})";


            int total = svc.ExecuteScalar<int>(sql, new { projectName = $"%{projectName}%", auth.UserId });

            sql += " order by createTime desc";
            sql += " offset @pageSize*(@pageIndex-1) rows fetch next @pageSize rows only";

            var data = svc.Query<UserProcedureDto>(sql, new { projectName = $"%{projectName}%", auth.UserId, pageSize, pageIndex });

            return new PagedResult<UserProcedureDto>() { code = 1, msg = "成功", total = total, data = data };
        }

        /// <summary>
        /// 获取单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public Result Get(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            return new Result() { code = 1, msg = "成功", data = data };
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public Result Post(UserProcedureRegisterDto dto)
        {
            var entity = mapper.Map<IEnumerable<UserProcedure>>(dto.Procedures);

            if (entity.Count() == 0) return new Result() { code = 1, msg = "数据为空" };


            if (svc.AddRange(entity))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = 1, msg = "失败" };
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public Result Put(int id, ProcedurePostDto dto)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            var entity = mapper.Map(dto, data);

            if (svc.Update(entity))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = -1, msg = "失败" };
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public Result Delete(int id)
        {
            var data = svc.Get(o => o.Id == id);

            if (data == null) return new Result() { code = -1, msg = "数据不存在" };

            data.Status = 0;

            if (svc.Update(data))
                return new Result() { code = 1, msg = "成功" };
            else
                return new Result() { code = -1, msg = "失败" };
        }

    }
}
